<template>
  <div class="el-upload">
    <el-form>
      <el-upload
          :limit="limit"
          action=""
          accept="image/*"
          :http-request="uploadFile"
          list-type="picture-card"
          :auto-upload="true"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :on-exceed="handleExceed"
          :before-remove="beforeRemove"
          ref="upload"
      >
        <i class="el-icon-plus avatar-uploader-icon"></i>
<!--        <img src="https://img-home.csdnimg.cn/images/20201124032511.png" width="146" height="146">-->
      </el-upload>
      <!--
      <el-form-item>
        <el-button size="small" type="primary" style="margin-top: 20px;" @click="submitUpload">点击上传</el-button>
      </el-form-item>
      -->
      <el-dialog :visible.sync="dialogVisible" append-to-body>
        <img width="100%" fit="contain" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form>
  </div>
</template>
<script>
// import { uploadImg, delUpIamge } from '@/api/publicSeries'
export default {
  props: {
    limit: Number,
    fileList: Array
  },
  data() {
    return {
      imageUrl: '',
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  methods: {
    submitUpload() { this.$refs.upload.submit() },
    uploadFile(e) {
      const file = e.file
      const size = file.size / 1024 / 1024 / 2
      console.log(size)
      if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
        })
        return
      } else if (size > 2) {
        this.$notify.warning({
          title: '警告',
          message: '图片大小必须小于2M'
        })
        return
      } else {
        const params = new FormData()
        params.append('file', file) // 图片
        console.log(params)
        this.$api.uploadFiles(params).then(res => {
          if (res.code === 0) {
            this.$message.success('上传成功')
            this.imageUrl = res.data.url
            this.$emit('getUrl', this.imageUrl)
          } else {
            this.$message.error('上传失败')
          }
        })
      }
    },
    // 图片上传超过数量限制
    handleExceed(files, fileList) {
      this.$message.error('图片数量超出限制!')
      console.log(files, fileList)
    },
    // 删除图片
    beforeRemove(file, fileList) {
      const url = file.url
      this.$emit('handleRemove', url)
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
}
</script>

